package xyz.zq.cloud.common.security.component;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;
import xyz.zq.cloud.common.core.constant.SecurityConstants;
import xyz.zq.cloud.common.security.service.CloudUser;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 根据 check_token 的结果转化用户信息
 *
 * @author hzq
 * @date 2020/4/28 21:19
 */
public class CloudUserAuthenticationConverter implements UserAuthenticationConverter {
    private static final String N_A = "N/A";

    /**
     * 提取有关要在访问令牌中使用的用户的信息（即用于资源服务器）。
     *
     * @param authentication 代表用户的认证
     * @return 代表有关用户的唯一信息的键值的映射
     */
    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new LinkedHashMap<>();
        response.put(USERNAME, authentication.getName());
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
        return response;
    }

    /**
     * Inverse of {@link #convertUserAuthentication(Authentication)}. 从map中提取身份验证。
     *
     * @param map 用户信息map
     * @return 代表用户的身份验证；如果不存在，则为null
     */
    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(USERNAME)) {
            Collection<? extends GrantedAuthority> authorities = getAuthorities(map);

            String username = (String) map.get(SecurityConstants.DETAILS_USERNAME);
            Integer id = (Integer) map.get(SecurityConstants.DETAILS_USER_ID);
            Integer deptId = (Integer) map.get(SecurityConstants.DETAILS_DEPT_ID);
            Integer companyId = (Integer) map.get(SecurityConstants.DETAILS_COMPANY_ID);
            CloudUser user = new CloudUser(id, deptId, companyId, username, N_A, true,
                    true, true, true, authorities);
            return new UsernamePasswordAuthenticationToken(user, N_A, authorities);
        }
        return null;
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        Object authorities = map.get(AUTHORITIES);
        if (authorities instanceof String) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
        }
        if (authorities instanceof Collection) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
                    .collectionToCommaDelimitedString((Collection<?>) authorities));
        }
        //权限必须是字符串或集合
        throw new IllegalArgumentException("Authorities must be either a String or a Collection");
    }
}
